﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Web;
using System.Web.Http.Controllers;
using System.Web.Http.Filters;
using Ttifa.Log;
using Ttifa.Infrastructure.Utils;

namespace Ttifa.WebApiBase.Filters
{
    public class ApiLogAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuting(HttpActionContext actionContext)
        {
            var dict = new Dictionary<string, object>();
            var param = actionContext.ActionArguments;
            dict.Add("IP", IPHelper.GetRequestIP());
            dict.Add("Url", actionContext.Request.RequestUri.AbsoluteUri);
            dict.Add("Method", actionContext.Request.Method);
            if (param.Count > 0)
            {
                dict.Add("Params", param);
            }
            actionContext.Request.Headers.Add("Log", JsonConvert.SerializeObject(dict));

            base.OnActionExecuting(actionContext);
        }

        public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
        {
            var log = actionExecutedContext.Request.Headers.GetValues("Log").First();
            var dict = JsonConvert.DeserializeObject<Dictionary<string, object>>(log);
            var result = actionExecutedContext.Response.Content.ReadAsStringAsync().Result;
            dict.Add("Result", result);
            var action = actionExecutedContext.Request.RequestUri;
            LogFactory.GetLogger().SetProperties(dict).Info(action.AbsolutePath);
            actionExecutedContext.Request.Headers.Remove("Log");

            base.OnActionExecuted(actionExecutedContext);
        }
    }
}